package com.difsonapps.android.marker.activities;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.difsonapps.android.marker.AppConstant;
import com.difsonapps.android.marker.CustomRequest;
import com.difsonapps.android.marker.IRefresher;
import com.difsonapps.android.marker.R;
import com.difsonapps.android.marker.UploadRequest;
import com.difsonapps.android.marker.R.layout;
import com.difsonapps.android.marker.R.menu;
import com.difsonapps.android.marker.app.AppController;
import com.difsonapps.android.marker.beans.Album;
import com.difsonapps.android.marker.beans.Photo;
import com.difsonapps.android.marker.upload.HttpFileUpload;
import com.difsonapps.android.marker.util.MarkerUtil;

import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Thumbnails;
import android.provider.MediaStore.Video;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

public class FormVideoActivity extends Activity {
	private final int SELECT_VIDEO = 1;
	static final int CAPTURE_VIDEO = 2;
	public static final String KEY_MODE_VIDEO_PICKER = "KEY_MODE_VIDEO_PICKER";
	public static final String MODE_GALLERY = "MODE_GALLERY";
	public static final String MODE_CAMERA = "MODE_CAMERA";
	
	Album album;
	
	EditText titleEditText;
	EditText descriptionEditText;
	VideoView videoView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_form_album);
		getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.main_color)));
		
		titleEditText = (EditText)findViewById(R.id.title);
		descriptionEditText = (EditText)findViewById(R.id.description);
		videoView = (VideoView)findViewById(R.id.video_view);
		
		videoView.setMediaController(new MediaController(this));
		//videoView.setVideoURI(Uri.parse("file://" + "/storage/sdcard/DCIM/Camera/VID_20141111_040439.mp4"));
		
		Intent i = getIntent();
		album = i.getParcelableExtra("album");
		
		String mode = i.getStringExtra(KEY_MODE_VIDEO_PICKER);
		if(mode==null || "".equals(mode)) mode = MODE_CAMERA;
		if(MODE_CAMERA.equals(mode)){
			Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
		        startActivityForResult(takeVideoIntent, CAPTURE_VIDEO);
		    }
		}else if(MODE_GALLERY.equals(mode)){
			Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
			photoPickerIntent.setType("video/*");
			startActivityForResult(photoPickerIntent, SELECT_VIDEO);
		}
		
		
		
	}
	
	String currentFilePath = null;
	
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
 
        switch(requestCode) { 
        case SELECT_VIDEO:
            if(resultCode == RESULT_OK){
				try {
					//showProgress();
					final Uri imageUri = imageReturnedIntent.getData();
					//toast(imageUri.getPath());
					String path = getPath(imageUri);
					//toast("path : "+path);
					Log.d("File Path", path);
					File file = new File(path);
					if(file.exists()){
						currentFilePath = path;
						videoView.setVideoURI(Uri.parse("file://" + path));
						//videoView.start();
						upload();
						uploadThumb();
					}
					//toast("Exist ? "+file.exists());
					/*if(file.exists()) currentSelectedFile = file;
					final InputStream imageStream = getContentResolver().openInputStream(imageUri);
					final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
					selectedImageView.setImageBitmap(selectedImage);
					//hideProgress();
					upload();*/
				} catch (/*FileNotFound*/Exception e) {
					e.printStackTrace();
					cancelAndClose();
				}
            }else{
            	cancelAndClose();
            }
            break;
        case CAPTURE_VIDEO:
        	if(resultCode == RESULT_OK){
				try {
					//showProgress();
					final Uri imageUri = imageReturnedIntent.getData();
					//toast(imageUri.getPath());
					String path = getPath(imageUri);
					//toast("path : "+path);
					Log.d("File Path", path);
					File file = new File(path);
					if(file.exists()){
						currentFilePath = path;
						videoView.setVideoURI(Uri.parse("file://" + path));
						//videoView.start();
						upload();
						uploadThumb();
					}
					//toast("Exist ? "+file.exists());
					/*if(file.exists()) currentSelectedFile = file;
					final InputStream imageStream = getContentResolver().openInputStream(imageUri);
					final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
					selectedImageView.setImageBitmap(selectedImage);
					//hideProgress();
					upload();*/
				} catch (/*FileNotFound*/Exception e) {
					e.printStackTrace();
					cancelAndClose();
				}
            }else{
            	cancelAndClose();
            }
        	break;
        }
    }
    public void btnSaveClick(View view){
		showProgress();
    	if(!uploadVideoEnd || !uploadThumbEnd) savePending = true;
    	else save();
    }
    boolean uploading = false;
    String uploadedPath = null;
    public void upload(){
    	uploading = true;
    	HttpFileUpload uploader=new HttpFileUpload(AppConstant.uploadVideoUrl, uploadSuccessCallback, uploadExceptionCallback);
		uploader.execute(currentFilePath);
    }
    public IRefresher<String> uploadSuccessCallback = new IRefresher<String>() {
		@Override
		public boolean refresh(String t) {
			try {
				uploading = false;
				JSONObject json = new JSONObject(t);
				String path = json.has("path")?json.getString("path"):null;
				if(path!=null && !path.equals("") && !path.equalsIgnoreCase("null")){
					uploadedPath = path;
					endUploads(UPLOAD_VIDEO);
					//if(savePending) save();
				}
				toast(path);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return false;
		}
	};
    public IRefresher<Exception> uploadExceptionCallback = new IRefresher<Exception>() {
		@Override
		public boolean refresh(Exception t) {
			uploading = false;
			toast(t.getMessage());
			return false;
		}
	};
	
	public boolean savePending = false;
	File thumbnailFile;
	String thumnail_file_saved;
	private void uploadThumb(){
		/*if(uploadedPath==null || uploadedPath.trim().equals("")){
			toast("No file uploaded");
			return;
		}*/
		if(currentFilePath==null) return;
		Bitmap thumbBitmap = ThumbnailUtils.createVideoThumbnail(currentFilePath, Thumbnails.MINI_KIND);
		thumbnailFile = MarkerUtil.saveToInternalSorage(thumbBitmap, this, "temp", "thumb.jpg");
		//toast("Thumb file : "+(thumbnailFile==null?"null":thumbnailFile.getAbsolutePath()));
		//Log.d("Thumb new path", thumbnailFile==null?"null":thumbnailFile.getAbsolutePath());
		
		Map<String, String> params = new HashMap<String, String>();
		UploadRequest jsObjRequest = new UploadRequest(
				AppConstant.uploadPhotoUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	//hideProgress();
                    	//toast("Response : "+response.toString());
                    	//Log.i("Test", response.toString());
                    	parseJsonUploadThumb(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	//hideProgress();
                    	toast("Error: " + error.getMessage());
                    	//Log.e("Test", error.getMessage());
                    	endUploads(UPLOAD_THUMB);
                    }
                },
                thumbnailFile
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	private void cancelAndClose(){
		finish();
	}
	
	private void parseJsonUploadThumb(JSONObject response){
		try {
        	//toast(response.toString());
            if(response.has("success")&&response.has("file")){
            	String success = response.getString("success");
            	toast(success);
            	String file = response.getString("file");
            	if(file!=null&&!file.trim().equals("")){
            		thumnail_file_saved = file;
            		//currentUploadeFile = file;
            		//toast("File : "+file);
            		//toast(getResources().getString(R.string.file_uploaded));

					endUploads(UPLOAD_THUMB);
            	}else{
            		toast(getResources().getString(R.string.error_while_uploading));
            	}
            }else if(response.has("error")){
            	String error = response.getString("error");
            	//TODO Show the error message in a textView and make it visible
            	//loginErrorView.setText(error);
            	//loginErrorView.setVisibility(View.VISIBLE);
            	toast(error);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //hideProgress();
	}
	private static final int UPLOAD_VIDEO = 1;
	private static final int UPLOAD_THUMB = 2;
	boolean uploadVideoEnd = false;
	boolean uploadThumbEnd = false;
	public void endUploads(int upload){
		if(upload==UPLOAD_VIDEO) uploadVideoEnd = true;
		if(upload==UPLOAD_THUMB) uploadThumbEnd = true;
		if(uploadVideoEnd && uploadThumbEnd){
			if(savePending) save();
		}
	}
	
	boolean saving = false;
	private void save(){
		if(uploadedPath==null || uploadedPath.trim().equals("")){
			toast("No file uploaded");
			//TODO Finish this activity
			return;
		}
		if(saving) return;
		saving = true;
		//uploadThumb();
		//if(true) return;
		
		/*String name = titleEditText.getText().toString();
		String description = descriptionEditText.getText().toString();
		
		if(album==null) {
			toast(getResources().getString(R.string.no_album_selected));
			return;
		}*/
		Map<String, String> params = new HashMap<String, String>();
        params.put("album_id", ""+(album==null?0:album.getId()));//TODO Put the id of the image selected here
        params.put("name", ""+titleEditText.getText().toString());
        params.put("description", ""+descriptionEditText.getText().toString());
        params.put("path", uploadedPath);
        params.put("thumbnail", thumnail_file_saved==null?"":thumnail_file_saved);
		//showProgress();
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				AppConstant.addVideoUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	hideProgress();
                    	toast("Response : "+response.toString());
                    	Log.i("Test", response.toString());
                    	parseJsonSave(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	hideProgress();
                    	saving = false;
                    	toast("Error: " + error.getMessage());
                    	//cancelAndClose();
                    	//Log.e("Test", error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	private void parseJsonSave(JSONObject response){
		try {
        	//toast(response.toString());
            if(response.has("success")&&response.has("video")){
            	JSONObject videoOject = response.getJSONObject("video");
            	com.difsonapps.android.marker.beans.Video video = com.difsonapps.android.marker.beans.Video.parseFromJsonObject(videoOject);
            	if(album==null) {
            		album = Album.parseFromJsonObject(response.getJSONObject("album"));
            	}
            	if(video!=null){
            		//toast("Closing : "+(video==null?"null":video.getName()));
            		close(album, video);
            	}else{
            		toast(getResources().getString(R.string.error_while_saving));
            		cancelAndClose();
            	}
            }else if(response.has("error")){
            	String error = response.getString("error");
            	toast(error);
            	cancelAndClose();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            cancelAndClose();
        }
	}
	
	private void close(Album album, com.difsonapps.android.marker.beans.Video video){
		Intent result = new Intent();
		Bundle b = new Bundle();
		b.putParcelable("album", album);
		b.putParcelable("video", video);
		result.putExtras(b);
		setResult(RESULT_OK, result);
		finish();
	}

    public String getPath(Uri uri) {
    	String[] projection = { MediaStore.Images.Media.DATA };
    	Cursor cursor = managedQuery(uri, projection, null, null, null);
    	startManagingCursor(cursor);
    	int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    	cursor.moveToFirst();
    	return cursor.getString(column_index);
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.form_album, menu);
		return true;
	}
	private void toast(String text){
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}
	ProgressDialog loadingProgressDialog;
	private void showProgress(){
		loadingProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.loading), getResources().getString(R.string.saving), true);
        loadingProgressDialog.setCancelable(true);
	}
	
	private void hideProgress(){
		if(loadingProgressDialog!=null) loadingProgressDialog.dismiss();
		loadingProgressDialog = null;
	}

}
